﻿/*
 * 文件名称：
 * 程序员：wangyun
 * 创建时间：2008/05/27
 * 
 * 功能说明：功能模块字段数据操作
 * 
 * 修改人员：
 * 
 * 修改日期：
 * 
 * 修改记录：
 */

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections;
using Whir.Common;
using Whir.Controls.ModelField;
using Whir.Publish;

public class ContentManage
{
    /// <summary>
    /// 获取添加功能模块字段的数据的SQL语句
    /// </summary>
    /// <param name="modelID">功能模块 ID</param>
    /// <param name="newDataTable">数据列表</param>
    /// <returns>返回功能模块字段添加的 SQL 语句</returns>
    public static string Add(int modelID, DataTable newDataTable)
    {
        Whir.BLL.Whir_Model modelBll = new Whir.BLL.Whir_Model();
        Whir.BLL.Whir_Field fieldBll = new Whir.BLL.Whir_Field();
        string tableName = modelBll.GetModel(modelID).tableName;            //获取表名
        DataTable dt = fieldBll.GetList(" ModelID = " + modelID).Tables[0];//根据功能模块获取该功能模块下的所有字段

        string str = "";
        str += "INSERT INTO " + tableName;
        str += "(";
        for (int i = 0; i < newDataTable.Rows.Count; i++)
        {
            str += newDataTable.Rows[i]["fieldName"].ToString() + ",";
        }
        str = str.TrimEnd(',');
        str += ")";
        str += " VALUES ";
        str += "(";
        for (int i = 0; i < newDataTable.Rows.Count; i++)
        {
            switch ((FieldType)int.Parse(newDataTable.Rows[i]["FieldType"].ToString()))
            {
                case FieldType.NumberType:
                case FieldType.MoneyType:
                    str += HttpContext.Current.Server.HtmlEncode(newDataTable.Rows[i]["FieldValue"].ToString()) + ",";
                    break;
                case FieldType.BoolType:
                case FieldType.ColorType:
                case FieldType.DateTimeType:
                case FieldType.FileType:
                case FieldType.LinkType:
                case FieldType.ListBoxType:
                case FieldType.MultipleHtmlTextType:
                case FieldType.MultipleTextType:
                case FieldType.PictureType:
                case FieldType.None:
                case FieldType.TextType:
                case FieldType.AreaType:
                case FieldType.PassWordType:
                    str += "'" + htmlEncode(newDataTable.Rows[i]["FieldValue"].ToString()) + "'" + ",";
                    break;
            }
        }
        str = str.TrimEnd(',');
        str += ")";
        return str.ToString();
    }

    /// <summary>
    /// 获取更新功能模块字段的数据的SQL语句
    /// </summary>
    /// <param name="modelID">功能模块 ID</param>
    /// <param name="fieldID">字段 ID</param>
    /// <param name="newDataTable">数据列表</param>
    /// <returns>返回功能模块字段更新的 SQL 语句</returns>
    public static string Update(int modelID, int fieldID, DataTable newDataTable)
    {
        Whir.BLL.Whir_Model modelBll = new Whir.BLL.Whir_Model();
        Whir.BLL.Whir_Field fieldBll = new Whir.BLL.Whir_Field();
        string tableName = modelBll.GetModel(modelID).tableName;            //获取表名

        string str = "";
        str += " UPDATE " + tableName;
        str += " SET ";
        for (int i = 0; i < newDataTable.Rows.Count; i++)
        {
            switch ((FieldType)int.Parse(newDataTable.Rows[i]["FieldType"].ToString()))
            {
                case FieldType.NumberType:
                case FieldType.MoneyType:
                    str += newDataTable.Rows[i]["fieldName"].ToString() + "= " + htmlEncode(newDataTable.Rows[i]["FieldValue"].ToString()) + ",";
                    break;
                case FieldType.BoolType:
                case FieldType.ColorType:
                case FieldType.DateTimeType:
                case FieldType.FileType:
                case FieldType.LinkType:
                case FieldType.ListBoxType:
                case FieldType.MultipleHtmlTextType:
                case FieldType.MultipleTextType:
                case FieldType.PictureType:
                case FieldType.None:
                case FieldType.TextType:
                case FieldType.PassWordType:
                case FieldType.AreaType:
                    str += newDataTable.Rows[i]["fieldName"].ToString() + "= '" + htmlEncode(newDataTable.Rows[i]["FieldValue"].ToString()) + "',";                
                    break;
            }

        }
        str = str.TrimEnd(',');
        str += " WHERE " + tableName + "_PID = " + fieldID;
        return str.ToString();
    }

    /// <summary>
    /// 获取删除功能模块字段的数据的SQL语句
    /// </summary>
    /// <param name="modelID">功能模块 ID</param>
    /// <param name="itemID">功能模块下的内容 ID</param>
    /// <returns>返回功能模块字段删除的 SQL 语句</returns>
    public static string Delete(int modelID, int itemID)
    {
        Whir.BLL.Whir_Model modelBll = new Whir.BLL.Whir_Model();
        Whir.BLL.Whir_Field fieldBll = new Whir.BLL.Whir_Field();
        string tableName = modelBll.GetModel(modelID).tableName;            //获取表名
        string str = "";

        str += " DELETE FROM ";
        str += tableName;
        str += string.Format(" WHERE {0} = {1}", tableName + "_PID", itemID);
        return str.ToString();
    }

    /// <summary>
    /// 获取删除功能模块字段的数据到回收站的SQL语句
    /// </summary>
    /// <param name="modelID">功能模块 ID</param>
    /// <param name="itemID">功能模块下的内容 ID</param>
    /// <returns>返回功能模块字段删除到回收站的 SQL 语句</returns>
    public static string DeleteInRecycleBin(int modelID, int itemID)
    {
        Whir.BLL.Whir_Model modelBll = new Whir.BLL.Whir_Model();
        Whir.BLL.Whir_Field fieldBll = new Whir.BLL.Whir_Field();
        string tableName = modelBll.GetModel(modelID).tableName;            //获取表名
        string str = "";

        str += " UPDATE " + tableName;
        str += " SET [IsRecycle] = 1 ";
        str += string.Format(" WHERE {0} = {1}", tableName + "_PID", itemID);
        return str.ToString();
    }

    /// <summary>
    /// 将字符串中的单引号字符编码
    /// </summary>
    /// <param name="word">字符串</param>
    /// <returns>返回编码后的字符串</returns>
    public static string htmlEncode(string word)
    {
        word = word.Replace("'", "&#34;");
        return word;
    }

    /// <summary>
    /// 将字符串中的单引号字符解码
    /// </summary>
    /// <param name="word">字符串</param>
    /// <returns>返回解码后的字符串</returns>
    public static string htmlDecode(string word)
    {
        word = word.Replace("&#34;", "'");
        return word;
    }

    /// <summary>
    /// 获取指定规则的功能模块表名
    /// </summary>
    public static string GetCustomTableName(string tableName)
    {
        string str = "Whir_U_" + tableName;
        return str.ToString();
    }

    /// <summary>
    /// 获取指定规则的功能模块的主键名称
    /// </summary>
    public static string GetCustomTablePrimaryKeyName(string tableName)
    {
        string str = tableName + "_PID";
        return str.ToString();
    }

    /// <summary>
    /// 获取指定规则的日期格式 yyyy-MM-dd
    /// </summary>
    public static string GetDateTimeFormat(object createDate)
    {
        return DateTime.Parse(createDate.ToString()).ToString("yyyy-MM-dd");
    }

    /// <summary>
    /// 获取自定义规则的日期格式 
    /// </summary>
    public static string GetDateTimeFormat(object createDate, string format)
    {
        if (string.IsNullOrEmpty(format))
            return "error datetime";
        else
            return DateTime.Parse(createDate.ToString()).ToString(format);
    }

    /// <summary>
    /// 返回刚添加的数据编号
    /// </summary>
    /// <param name="modelId">功能模块ID</param>
    /// <returns>返回编号</returns>
    public static int GetTopItemID(int modelId)
    {
        Whir.BLL.Whir_Model bll = new Whir.BLL.Whir_Model();
        Whir.Model.Whir_Model model = new Whir.Model.Whir_Model();
        model = bll.GetModel(modelId);
        string sql = "SELECT TOP 1 {0} FROM {1} ORDER BY {0} DESC";
        sql = string.Format(sql, GetCustomTablePrimaryKeyName(model.tableName), model.tableName);
        return Convert.ToInt32(Whir.SQLServerDAL.DbHelperSQL.GetSingle(sql).ToString());
    }

    /// <summary>
    /// 验证字段是否在表单列表中存在
    /// </summary>
    /// <param name="modelID">功能模块ID</param>
    /// <param name="fieldID">字段ID</param>
    /// <returns>返回状态（True:存在；False:不存在）</returns>
    public static bool FieldInModelFormCheck(int modelID, int fieldID)
    {
        Whir.BLL.Whir_ModelForm bllFormModel = new Whir.BLL.Whir_ModelForm();
        Whir.Model.Whir_ModelForm modelFormModel = new Whir.Model.Whir_ModelForm();
        DataTable dt = bllFormModel.GetModelForms(modelID);
        bool flag = false;
        foreach (DataRow row in dt.Rows)
        {
            string[] fieldIDs = bllFormModel.GetFieldIDsAll(int.Parse(row["ModelFormID"].ToString())).Split(',');

            for (int i = 0; i < fieldIDs.Length; i++)
            {
                if (fieldID == int.Parse(fieldIDs[i].ToString()))
                {
                    flag = true;
                    break;
                }
            }
        }

        return flag;
    }

    /// <summary>
    /// 验证表单是否在栏目中存在
    /// </summary>
    /// <param name="modelFormID">表单ID</param>
    /// <returns>返回状态（True:存在；False:不存在）</returns>
    public static bool ModelFormInColumnCheck(int modelFormID)
    {
        bool flag = false;

        Whir.BLL.Whir_Column bll = new Whir.BLL.Whir_Column();
        Whir.Model.Whir_Column model = new Whir.Model.Whir_Column();
        flag = bll.GetColumns(modelFormID);
        return flag;
    }

    /// <summary>
    /// 获取表单的数据
    /// </summary>
    public static DataTable GetDataTableFromRepeater(Repeater repeaterControl)
    {
        DataRow row;
        DataTable dataTable = new DataTable();
        dataTable.Columns.Add("FieldID");
        dataTable.Columns.Add("FieldName");
        dataTable.Columns.Add("FieldValue");
        dataTable.Columns.Add("FieldType");
        dataTable.Columns.Add("FieldLevel");

        foreach (RepeaterItem item in repeaterControl.Items)
        {
            FieldControl control = (FieldControl)item.FindControl("Field");
            row = dataTable.NewRow();
            row["FieldID"] = control.FieldID;
            row["FieldName"] = control.FieldName;
            row["FieldValue"] = control.Value;
            row["FieldType"] = (int)control.ControlType;
            row["FieldLevel"] = control.FieldLevel;
            dataTable.Rows.Add(row);
        }

        return dataTable;
    }

    /// <summary>
    /// 发布指定栏目和指定数据ID的页面
    /// </summary>
    /// <param name="columnId">栏目ID</param>
    /// <param name="itemID">数据ID</param>
    /// <returns>返回生成状态</returns>
    public static string[] publish(int columnId, int itemID, Page page)
    {
        string[] strResult = new string[2];
        Whir.BLL.Whir_Column bll = new Whir.BLL.Whir_Column();
        Whir.Model.Whir_Column column = bll.GetModel(columnId);
        CreateHtml index = new CreateHtml(column, page);
        index.itemID = itemID.ToString();
        strResult = index.Bind();
        return strResult;
    }

    public static string[] publish(int columnId, Page page)
    {
        string[] strResult = new string[2];
        Whir.BLL.Whir_Column bll = new Whir.BLL.Whir_Column();
        Whir.Model.Whir_Column column = bll.GetModel(columnId);
        if (column.listTemp != "" || column.defaultTemp != "" || column.contentTemp != "")
        {
            CreateHtml index = new CreateHtml(column, page);
            index.beginDate = "";
            index.endDate = "";
            index.itemID = "";
            strResult = index.Bind();
        }
        else
        {
            strResult[0] = "true";
        }
        return strResult;
    }
}
